﻿using Great_Eggspectations.DAL;
using Great_Eggspectations.ViewModels;
using Microsoft.VisualBasic.FileIO;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Great_Eggspectations.Controllers
{
    public class HomeController : Controller
    {
        private BirdbrainContainer db = new BirdbrainContainer();

        public ActionResult Index(int page = 1, int pageSize = 25)
        {
            return View(new HomeIndexViewModel
            {
                TransactionsIndexTableViewModel = new TransactionsIndexTableViewModel(db.Transactions, page, pageSize),

                PartnersPagedList = new PagedList<Partner>(db.Partners.OrderBy(i => i.Name).ToList(), page, pageSize),
                ProductsPagedList = new PagedList<Product>(db.Products.OrderBy(i => i.Name).ToList(), page, pageSize),

                PartnerTags = getTags(db.Partners.Select(p => p.CSVTags)),
                ProductTags = getTags(db.Products.Select(p => p.CSVTags))
            });
        }

        private List<Tuple<string, int>> getTags(IQueryable<string> tagCSVs)
        {
            var retVal = new List<Tuple<string, int>>();
            var tags = tagCSVs.ToList().SelectMany(ts => ts.ToUpper().Split(','));

            foreach (var tag in tags.Distinct())
            {
                retVal.Add(new Tuple<string, int>(tag, tags.Count(t => t == tag)));
            }
            return retVal;
        }

        public ActionResult About()
        {
            ViewBag.Message = "About this site.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "About me.";

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}